package top.huhuiyu.springboot.study.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.huhuiyu.springboot.study.config.MxnzpConfig;
import top.huhuiyu.springboot.study.entity.joke.DailyWord;
import top.huhuiyu.springboot.study.entity.joke.TbDailyWord;
import top.huhuiyu.springboot.study.mapper.joke.TbDailyWordMapper;
import top.huhuiyu.springboot.study.service.DailyWordService;
import top.huhuiyu.springboot.study.util.JsonUtils;

/**
 * @author 胡辉煜
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DailyWordServiceImpl implements DailyWordService {
  private final RestTemplate restTemplate;
  private final TbDailyWordMapper tbDailyWordMapper;

  @Override
  public DailyWord getDailyWord() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APPID);
    headers.add("app_secret", MxnzpConfig.APPSECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    String result = restTemplate.exchange(MxnzpConfig.DAILY_WORD_URL + 10, HttpMethod.GET, entity, String.class).getBody();
    return JsonUtils.parse(result, DailyWord.class);
  }

  @Override
  public int saveDailyWord() {
    DailyWord dailyWord = getDailyWord();
    dailyWord.getData().forEach(data -> {
      TbDailyWord word = new TbDailyWord();
      word.setContent(data.getContent());
      word.setAuthor(data.getAuthor());
      tbDailyWordMapper.save(word);
    });
    return dailyWord.getData().size();
  }


}
